<template>
  <el-popover
  :width="300"
  trigger="click"
  placement="bottom-start"
>
  <template #reference>
    <el-input v-model="selectedText" readonly />
  </template>
  <el-tree style="width:100%;height:100%;"
      :data="treeData" 
      ref="treeRef"
      node-key="id"
      show-checkbox
      default-expand-all
      :default-checked-keys="treeDefaultChecked"
      :check-strictly="true"
      @check-change="handleCheckChange"
      :check-on-click-node="true"
  >
  </el-tree>
</el-popover>
</template>
<script lang="ts">
import { defineComponent,onMounted,reactive, ref, toRefs, watch} from 'vue'
import request from '/@/utils/request'

export default defineComponent({
  name: 'departmentMultSelectTree',
  emits: ['treeSelected'],
  props: {
      parentId: String,
      selectedText: String,
      treeDefaultChecked: Array
  },
  setup(props, context) {
      const state = reactive({
          loading: false,
          treeData: [],
      })
      const loadData = ()=>{
          state.loading = true
    request.get('/system/department/tree',{
              params:{
                  parentId: (props.parentId||'')
              }
          }).then(res => {
      state.treeData = res?.data || []
     }).finally(()=>{
      state.loading = false
    })
      }
      const init = ()=>{
          state.treeData = [];
      }
      watch(()=>props.parentId,()=>{
          init();
          loadData();
      })

      watch(()=>props.treeDefaultChecked,()=>{
          if(!props.treeDefaultChecked || props.treeDefaultChecked.length == 0){
            treeRef.value?.setCheckedKeys([]);
          }
      })

      onMounted(()=>{
          loadData();
      })
      const selectRef = ref();
      const treeRef = ref();
      const handleCheckChange = (data:any)=>{
          var datas = [];
          treeRef.value.getCheckedNodes().forEach((department: any) => {
              if (department.dprtType === "1") {
                  datas.push({
                      id: department.id,
                      label: department.label,
                  });
              }
          });
          if (datas.length === 0) {
              datas = treeRef.value.getCheckedNodes().map((department: any)=>{
                  return {
                      id: department.id,
                      label: department.label,
                  }
              })
          }
          context.emit("treeSelected", datas);
      }
      return {
          ...toRefs(state),
          ...toRefs(props),
          handleCheckChange,
          selectRef,
          treeRef,
      }
  }
})
</script>
